import allure
import requests

from src.api.author.author import Author
from src.api.base_api import BaseApi

# todo 合并， 健华
from src.utils.get_today_time import get_today_time_start, get_today_time_end


class Sample(BaseApi):
    def __init__(self, base_url):
        super().__init__(base_url)

    def get_last_receiver_info(self, author_id=99553932701):
        '''
        获取上次收货信息
        https://ck-medium-api-test.cds8.cn/v1/sample/getLastReceive?author_id=99553932701
        '''
        url = 'https://ck-medium-api-test.cds8.cn/v1/sample/getLastReceive?author_id=99553932701'
        params = {
            'author_id': author_id
        }
        json_res = self.send(method='GET', path='sample/getLastReceive', params=params)
        print()
        return json_res

    @allure.step('创建样品单')
    def create(self, author_info, products, receiver_info, user_info, platform='dy', target_type=0, **kwargs):
        '''
        创建样品单:https://api-mock.limayao.com/project/494/interface/api/17741
        author.list_dropdown_cooperate(user_id=user_id, author_id=author_id, platform='dy')
        [Goods().list(author_id=author_id)]
        self.get_last_receiver_info(author_id=author_id)
        Dept().users_list(user_id=user_id)
        当target_type为0时，寄样对象为达人
        当为1时，寄样对象为团长
        '''

        url = 'https://ck-medium-api-test.cds8.cn/v1/sample'
        json_data = {
            'author_info': author_info,
            'products': [products],
            'receiver_info': receiver_info,
            'user_info': user_info,
            'platform': platform,
            'remark': {
                "remark": "",
                "items": [],
                "file_info": []
            },
            'target_type': target_type,
            'colonel_info': {
                "colonel_buyin_id": ""
            },
            'order_sn': '',

        }
        if 'colonel_info' in kwargs:
            json_data['colonel_info'] = kwargs.get('colonel_info')
        json_res = self.send(method='POST', path='sample', json=json_data)
        return json_res

    def list(self, platform='dy', order_sn="", product_id="", shop_ids="", author_id="", dept_id="", medium_id="",
             repeat_send=0, receiver="", logistics_id="", start_time="", end_time="", **kwargs):
        '''
        获取样品单的情况，只要我们在生成样品单的同时，立马获取第一张样品单就能获取样品单单号了
        https://ck-medium-api-test.cds8.cn/v1/sample

        '''
        url = 'https://ck-medium-api-test.cds8.cn/v1/sample'
        params = {
            'platform': platform,
            'status': 0,
            'order_sn': order_sn,
            'product_id': product_id,
            'shop_ids': shop_ids,
            'author_id': author_id,
            'dept_id': dept_id,
            'medium_id': medium_id,
            'receiver': receiver,
            'logistics_id': logistics_id,
            'start_time': start_time,
            'end_time': end_time,
            'target_type': 0,
            'repeat_send': repeat_send,
            'erp_status': 0,
            'page': 1,
            'size': 50
        }
        if 'target_type' in kwargs:
            params['target_type'] = kwargs.get('target_type')
        json_res = self.send(method='GET', path='sample', params=params)
        print()
        return json_res

    @allure.step('线下发货')
    def offline_delivery(self, order_sn, offline_remark=''):
        '''
        线下发货
        https://ck-medium-api-test.cds8.cn/v1/sample/offline_delivery
        '''
        url = 'https://ck-medium-api-test.cds8.cn/v1/sample/offline_delivery'
        json_data = {
            "order_sn": order_sn,
            "l_id": "",
            "logistics_type": "",
            "logistics_id": "",
            "logistics_ext": "",
            "offline_remark": offline_remark
        }
        json_res = self.send(method='post', path='sample/offline_delivery', json=json_data)
        print()
        return json_res

    @allure.step('审核样品单')
    def update_examine(self, order_sn, examine_status, **kwargs):
        '''
        更新样品单状态：通过审核
        https://ck-medium-api-test.cds8.cn/v1/sample/updateExamine
        参数：
        order_sn: 订单号
        examine_status: number 1：待审核，2：审核通过，3：审核不通过
        refuse_reason: str 非必须 拒绝理由，在审核不通过时必须
        '''
        json_data = {
            "order_sn": [order_sn],
            "examine_status": examine_status,
        }
        # 如果examine_status为3（审核不通过），并且没有提供refuse_reason，则抛出异常或错误处理
        if examine_status == 3 and 'refuse_reason' not in kwargs:
            raise ValueError("当examine_status为3时，必须提供refuse_reason参数")
            # 如果提供了refuse_reason，或者examine_status为2（审核通过），则将其加入json_data
        if 'refuse_reason' in kwargs or examine_status == 2:
            json_data["refuse_reason"] = kwargs.get('refuse_reason')
            # 发送请求
        json_res = self.send(method='PUT', path='sample/updateExamine', json=json_data)
        return json_res

    @allure.step("批量删除样品单")
    def batch_del(self, order_sn):
        """
        批量删除样品单：https://api-mock.limayao.com/project/494/interface/api/23552
        接口路径：/v1/sample/batchDel
        order_sn	string []	非必须     订单编号	item 类型: string
        """
        json_data = {"order_sn": order_sn}
        json_res = self.send(method='POST', path='sample/batchDel', json=json_data)
        return json_res

    @allure.step("单号识别")
    def distinguish(self, logistics_id):
        """
        单号识别：https://api-mock.limayao.com/project/494/interface/api/26166
        """
        params = {"logistics_id": logistics_id}
        json_res = self.send(method='GET', path='sample/distinguish', params=params)
        return json_res

    @allure.step("添加物流")
    def express_add(self, order_sn, logistics_id, logistics_type):
        """
        添加物流：https://api-mock.limayao.com/project/494/interface/api/33110
        """

        json_data = {"order_sn": order_sn, "logistics_id": logistics_id, "logistics_type": logistics_type}
        json_res = self.send(method='POST', path='content/sample/express/add', json=json_data)
        return json_res

    @allure.step("寄样详情")
    def detail(self, order_sn):
        """
        寄样详情：https://api-mock.limayao.com/project/494/interface/api/33058
        """

        params = {"order_sn": order_sn}
        json_res = self.send(method='GET', path='sample/detail', params=params)
        return json_res

    @allure.step("样品单回收")
    def recovery(self, logistics_id, logistics_type, order_sn, recovery_remark):
        """
        样品单回收：https://api-mock.limayao.com/project/494/interface/api/23860
        """

        json_data = {"logistics_id": logistics_id, "logistics_type": logistics_type, "order_sn": order_sn,
                     "recovery_remark": recovery_remark}
        json_res = self.send(method='POST', path='sample/recovery', json=json_data)
        return json_res

    @allure.step("更新样品")
    def update(self, author_id, author_name, receiver_info, remark, product_id,
               product_title, order_sn):
        """
        更新样品：https://api-mock.limayao.com/project/494/interface/api/23568
        """
        json_data = {
            "author_info": {
                "author_id": author_id,
                "author_name": author_name
            },
            "receiver_info": receiver_info,
            "remark": {
                "remark": remark
            }, "products": [
                {
                    "product_id": product_id,
                    "product_title": product_title
                }],
            "order_sn": order_sn
        }
        print(json_data)
        json_res = self.send(method='POST', path='sample/update', json=json_data)
        return json_res

    @allure.step("收件信息格式化")
    def receiveInfo(self, text):
        """
        收件信息格式化：https://api-mock.limayao.com/project/494/interface/api/24074
        """

        params = {"text": text}
        json_res = self.send(method='GET', path='sample/receiveInfo', params=params)
        return json_res

    @allure.step("同步ERP")
    def batch_sync_to_erp(self, order_sn):
        """
        批量删除样品单：https://ck-medium-api-test.cds8.cn/v1/sample/batchSyncToERP
        接口路径：/v1/sample/batchDel
        order_sn	string []	非必须     订单编号	item 类型: string
        """
        json_data = {"order_sn": order_sn}
        json_res = self.send(method='POST', path='sample/batchSyncToERP', json=json_data)
        return json_res

    def list_calSampleStatistics(self, platform='dy', target_type=0, start_time=get_today_time_start(),
                                 end_time=get_today_time_end(),**kwargs):
        '''
        用于在合作管理-样品根据-数据详情处获取数据列表
        url=https://ck-medium-api-test.cds8.cn/v1/sample/calSampleStatistics
        get
        参数说明：
        start_time：使用秒来表达时间：1715788800
        target:0代表达人寄样类型，1代表团长寄样类型
        默认为当天的寄样数
        '''
        params = {
            'platform': platform,
            'target_type': target_type,
            # 'start_time': start_time,
            # 'end_time': end_time
        }
        for k,v in kwargs.items():
            params[k] = v

        res_json = self.send(method='get', path='sample/calSampleStatistics', params=params)

        return res_json


if __name__ == '__main__':
    # order_sn = Sample().list()
    # Sample().update_examine(order_sn=order_sn, examine_status=2)
    # author_id = Author().author_list(keyword='milanjia830', platform='dy')
    # Sample().create_sample(user_id=34641, author_id=author_id)
    # Sample().get_last_receiver_info()

    # order_sn = ["SPETTT20240515095135I2FJFS2NM"]
    # aa = Sample(base_url='https://ck-medium-api-test.cds8.cn/v1/').batch_del(order_sn=order_sn)

    aa = Sample(base_url='https://ck-medium-api-test.cds8.cn/v1/').list()
    print(aa)
